//学术任职
<template>
  <div class="module_">
    <div class="mb8">
      <search @clearSearch='clearSearch'>
        <el-form label-width='93px' inline autocomplete="off" :model="pageparm" class="search_box">
          <el-form-item label="任职人姓名">
            <inputSearch ref="search_e" placeholder="请输入任职人姓名搜索" @onChange='searchChane($event,"employees_id")'  />
          </el-form-item>
          <el-form-item label="科室">
            <inputSearch ref="search_d" type="departments" @onChange='searchChane($event,"department_id")'  />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索" @change='searchChane($event,"review_status")'>
              <el-option
                v-for="item in reviewStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button slot="footer" size="medium" type="primary" @click="handle(null,{},3)">新增学术任职</el-button>
      </search>
    </div>
    <el-table
      :data="tableData"
      class="flex-1"
      height="100%" size="medium" 
      border 
      highlight-current-row
      v-loading="tableLoading"
      stripe
      @sort-change="tableSortChange">  
      <el-table-column
        align="center"
        v-for="(item,i) in headerList"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :min-width="item.width"
        :fixed="i === 0 ? true: false"
        show-overflow-tooltip
        sortable="custom">
        <template slot-scope="scope">
          <template v-if="item.prop === 'employees_id'">
            {{ scope.row.employee?scope.row.employee.name:'' }}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review_status === 2" class="c-red">{{reviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}} </span>
            <span v-else>{{reviewStatusObj[scope.row.review_status]}}</span>
          </template>
          <template v-else-if="item.prop === 'on_job'">
            {{ scope.row.on_job === 1 ? '在职':'离职' }}
          </template>
          <template v-else>
           {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="证书图片" min-width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.attachment && scope.row.attachment.length > 0">
            <el-image
              v-for="v in scope.row.attachment" :key="'Files'+ v.id"
              :src="uploadUrl + v.path" 
              :preview-src-list="srcListMethods(scope.row.attachment)">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="150">
        <!-- v-if="adminShow || !adminShow && scope.row.review_status !== 1" -->
        <div slot-scope="scope" class="tx-r" v-if="scope.row.delete">
          <el-tooltip  effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0">
            <el-button v-permission="{action:'学术任职审核',effect:'delete'}" type="primary" @click="examine_btns(scope.row,1)" size="small"  icon="el-icon-help" circle></el-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="修改信息" placement="bottom-end">
            <el-button size="small"  @click="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="删除" placement="bottom-end">
            <el-button size="small" type="danger" @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="740px" @close='dialogClose'
    :close-on-click-modal='false'
    :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">{{dialogTitle}}</h2>
      <el-form autocomplete="off"  label-width="120px" :model="editForm" class="form_flex">
        <el-form-item
          v-for="(v, i) in editHeaderList"
          :key="i"
          :label="v.label"
          :class="v.required ? 'tip' : ''">
          <inputSearch :options="{type:'leader'}" v-if="v.prop === 'employees_id'" ref="e_Search" @onChange='nameChange' :middleList='middleList' />
          <inputSearch v-else-if="v.prop === 'department_name'" ref="departmentSearch" type="departments" @onChange="departmentsChange" />
          <el-radio-group v-else-if="v.prop === 'on_job'" v-model="editForm[v.prop]">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="2">离职</el-radio>
          </el-radio-group>
          <el-date-picker
            v-else-if="v.prop === 'start_time' || v.prop === 'end_time'"
            size="medium"
            v-model="editForm[v.prop]"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            :picker-options='pickerOptions[v.prop]'
            @change="changeDate($event,v.prop)">
          </el-date-picker>
          <el-input
            v-else
            size="medium"
            :type="v.type"
            autosize
            clearable
            v-model="editForm[v.prop]"
            @mousewheel.native.prevent
            :placeholder="'请输入' + v.label"/>
            <div v-if=" v.prop === 'office_years'" style="lineHeight:1;color:#999999">届次为整数！</div>
        </el-form-item>
        <el-form-item label="证书图片" class="tip">
          <el-upload
            list-type="picture-card"
            class="upload"
            multiple
            action="/"
            accept="image/*"
            :on-change='onChangeFile'
            :on-remove="onRemoveFile"
            :auto-upload="false"
            ref="upload"
            :file-list='fileList'>
             <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="已上传图片" v-if="editForm.attachment && editForm.attachment.length > 0">
          <div>
            <span class="imgbox" v-for="v in editForm.attachment" :key='"edit" + v.id'>
              <el-image
                class="image"
                :src="uploadUrl + v.path" 
                :preview-src-list="srcListMethods(editForm.attachment)"
                :z-index='3000'>
              </el-image>
              <i class="el-icon-circle-close delIcon" @click="delFiles(v)"></i>
            </span>
          </div>
        </el-form-item>
      </el-form> 
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>

    <el-image-viewer
      v-if="imgObj.showImg"
      :on-close="()=>{imgObj.showImg=false}"
      :url-list="imgObj.urlList" />

      <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' />
  </div>
</template>

<script>

import {
    Apiacademicoffice,
    ApiacademicofficeAdd,
    ApiacademicofficePut,
    ApiacademicofficeDel,
    ApiacademicofficeCheck,
} from '@/api'
import {reviewStatus,reviewStatusObj} from "@/assets/js"
import { debounce,adminShow } from "@/utils/index";
import {isPosInteger} from '@/utils/test'
import {uploadUrl} from '@/api/request'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'holdoffice_holdoffice',
  components:{
    ElImageViewer
  },
  computed:{
    editHeaderList(){
      return this.headerList.filter(item => item.prop !== "review_status")
    }
  },
  data(){
    return{
      adminShow:adminShow(),
      uploadUrl:uploadUrl(),
      reviewStatus,
      reviewStatusObj,
      tableData:[], 
      editFormVisible: false, 
      editForm: {},  //修改或者查看详情

      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null, 
        sort_order: 'desc' ,
      },
      tableLoading: false,

      btnLoading: false,

      headerList: [
        {
          prop: "employees_id",
          label: "任职人",
          type: "number",
          width: "150",
          required: true,
          
        },{
          prop: "department_name",
          label: "科室",
          type: "number",
          width: "150",
          required: true,
          
        },{
          prop: "review_status",
          label: "状态",
          type: "number",
          width: "180",
          required: true,
          
        },{
          prop: "office_unit",
          label: "任职单位",
          type: "text",
          width: "250",
          required: true,
          
        },{
          prop: "position",
          label: "任职职位",
          type: "text",
          width: "200",
          required: true,
          
        },{
          prop: "start_time",
          label: "任职开始日期",
          type: "text",
          width: "150",
          required: true,
          
        },{
          prop: "end_time",
          label: "任职终止日期",
          type: "text",
          width: "150",
          required: true,
          
        },{
          prop: "office_years",
          label: "届次",
          type: "number",
          width: "150",
          required: true,
          
        },{
          prop: "on_job",
          label: "是否在职",
          type: "text",
          width: "150",
          required: true,
          
        }
      ],
      rules:['employees_id','position','start_time','office_years','office_unit'],

      middleList:[],

      fileList:[], //文件

      imgObj:{
        showImg: false,
        urlList:[]
      },

      examine_item:{
        view:false
      },

      pickerOptions:{
        start_time:{},
        end_time:{},
      },

      dialogTitle: '',
    }
  },
  mounted(){
    this.getList()
  },
  methods:{
    srcListMethods(arr){
      return arr.reduce((array,item)=>{
        array.push( this.uploadUrl + item.path)
        return array
      },[])
    },
    changeDate(t){
      this.pickerOptions = {
        start_time:{
           disabledDate: (time) => {
            if (this.editForm.end_time) {
              return (time.getTime() >= new Date(this.editForm.end_time).getTime());
            }
            // else{
            //   return time.getTime() < (Date.now() - 86400000)
            // }
          }
        },
        end_time:{
          disabledDate: (time) => {
            if (this.editForm.start_time) {  // 开始日期
              return (time.getTime() < new Date(this.editForm.start_time).getTime() - 86400000);
            }
            // else{
            //   return time.getTime() < Date.now() - 86400000
            // }
          }
        },
      }
    },
    examine_btns(item,i){
      this.examine_id = item.id
      if(i > 1){
        this.examine_item.review_status = item.review_status
        this.examine_item.review_comment = item.review_comment
        this.examine_item.view = true
      }else{
        // this.examine_item.review_status = null
        // this.examine_item.review_comment = null
        this.examine_item.view = false
      }
      this.$refs.examine.examineShow = true

    },
    //审核
    examineSubmit(options){
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      options.id = this.examine_id
      ApiacademicofficeCheck(options,options.id).then(res => {
        this.getList()
      }).catch(()=>{
        this.$message.error('服务器错误，请重新提交');   
      }).finally(()=>{
        loading.close()
      })
    },
    delFiles(v){
      this.editForm.attachment = this.editForm.attachment.filter(item => item.id !== v.id)
    },
    uploadFiles(url,arr){
      let list
      if(arr.length > 1){
        list = arr.reduce((array,item)=>{
          if(item.path !== url){
            array.push( this.uploadUrl + item.path)
          }
          return array
        },[this.uploadUrl + url])
      }else{
        list = [this.uploadUrl + url]
      }
      this.imgObj.urlList = list
      this.imgObj.showImg = true
      // ApiupLoadFiles(url).then(res => {
      //   let a = document.createElement("a")
      //   a.href = URL.createObjectURL(res)
      //   a.download = name
      //   a.click()
      //   URL.revokeObjectURL(a.href)
      // })
    },
    onChangeFile(file, fileList){
      this.fileList.push(file)
    },
    onRemoveFile(file, fileList){
      this.fileList = fileList
    },
    
    tableSortChange(column){
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      }else{
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      this.getList()
    },
    //搜索
    clearSearch(){
      this.$refs.search_d.clear()
      this.$refs.search_e.clear()
    },
    searchChane(i,val){
      this.pageparm[val] = i
      this.pageparm.page = 1
      this.getList()
    },
    //分页
    callFather(pageparm){
      this.pageparm.page = pageparm.page
      this.pageparm.perPage = pageparm.perPage
      this.getList()
    },
    getList(){
      this.tableLoading = true
      Apiacademicoffice(this.pageparm).then(({data,page}) => {
        this.tableData = data || []
        this.pageparm.total = page.total
        this.tableLoading = false
      }).catch(()=>{
        this.tableLoading = false
      })
    },
    handle(index,value,i){
      this.editForm = {...value}
      this.editFormVisible = true
      this.dialogTitle = '新增学术任职'
      if(i == 2){
        this.dialogTitle = '编辑学术任职'
        delete this.editForm.department
        delete this.editForm.review
        this.$nextTick(()=>{
          this.middleList = [{employees_id: value.employees_id,employee:{name:value.employee.name}}]
          this.$refs.departmentSearch[0].departments_id = this.editForm.department_id || null;
        })
      }else{
        if(!this.adminShow) this.editForm.department_id = this.$store.state.userInfo.department_id 
      }
      this.changeDate()
    },
    nameChange(id){
      this.editForm.employees_id = id
    },
    departmentsChange(id){
      this.editForm.department_id = id
    },
    dialogClose(){
      this.$refs.e_Search[0].clear()
      this.$refs.departmentSearch[0].clear()
      this.fileList = []
    },
    deleteUser(index,value){
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApiacademicofficeDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }).finally(()=>{
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    submit : debounce(function(){   //提交  修改或新增
      const options = this.editForm
      for (const key of this.rules) {
        if(!options[key] && options[key] !== 0){
          this.$message({
            type: 'error',
            message: '必填信息请填写完整！'
          });
          return
        }
      }
      if(!isPosInteger(options.office_years)){
        this.$message({
            type: 'error',
            message: '届次为整数！'
          });
        return
      }
      if(this.fileList.length === 0 && (!options.attachment || options.attachment.length === 0)){
        this.$message({
            type: 'error',
            message: '请上传证书图片'
          });
        return
      }
      this.btnLoading = true
      const formData = new FormData()
      formData.append('department_id',options.department_id)
      formData.append('employees_id',options.employees_id)
      formData.append('position',options.position)
      formData.append('start_time',options.start_time)
      formData.append('office_years',options.office_years)
      formData.append('office_unit',options.office_unit)
      formData.append('on_job',options.on_job)
      formData.append('end_time',options.end_time)
      if(this.fileList.length > 0){
        this.fileList.forEach(item=>{
          formData.append('files[]',item.raw)
        })
      }
      if(options.id){   //有ID就是修改
        if(options.attachment && options.attachment.length > 0){
            options.attachment.forEach(item =>{
              formData.append('file_name[]',item.file_name)
              formData.append('file_path[]',item.file_path)
            })
        }else{
          formData.append('file_name[]',[])
          formData.append('file_path[]',[])
        }
        ApiacademicofficePut(formData,options.id,{
            headers:{'Content-Type':'multipart/form-data'}
        }).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.editFormVisible = false
          this.getList()
        }).catch(()=>{
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        }).finally(()=>{
            this.btnLoading = false
        });
      }else{
        ApiacademicofficeAdd(formData,{
            headers:{'Content-Type':'multipart/form-data'}
        }).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.editFormVisible = false
          this.getList()
        }).catch(()=>{
          this.$message({
            type: 'error',
            message: '添加失败!'
          });
        }).finally(()=>{
            this.btnLoading = false
        });
      }
    },800,true)
  },

}
</script>
<style lang='less' scoped>
.upload{
    width: 500px;
}
.underline {
    text-decoration: underline;
}
.inconfont{
    font-size: 20px;
}
 .el-image{
  display: inline-block;
  width: 40px;
  height: 40px;
  margin-right: 4px;
}
/deep/.el-upload-list--picture-card .el-upload-list__item{
  width: 120px;
  height: 120px;
}
/deep/.el-upload--picture-card{
  width: 120px;
  height: 120px;
  line-height:120px;
}
.imgbox{
  display: inline-block;
  position: relative;
  .image{
  width: 120px;
  height: 120px;
  }
  .delIcon{
    position: absolute;
    right: 4px;
    top: 0;
    color: #FC3711;
    font-size: 20px;
    opacity: 0;
    transition: 0.5s;
  }
}
.imgbox:hover{
  .delIcon{
    opacity: 1;
  }
}

</style>